#!/usr/bin/env python
# -*- coding: utf8 -*-

import translations, re, httplib, urllib, time, shutil, json
import os
os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))

#http://translate.google.ru/translate_tts?ie=UTF-8&q=Warning&tl=en
lang = 'en'
voice = 'English (British) - male'

def fetchMp3(path, text, lang):
    if text.count('&'): return
    params = {'v': voice, 't': text, 'f': 'mp3'}
    headers = {
'Accept':'application/json, text/javascript, */*; q=0.01',
'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',
# Cookie:hsfirstvisit=http%3A%2F%2Fwww.readspeaker.com%2F|https%3A%2F%2Fwww.google.ru%2F|1387967455756; _icl_current_language=en; __hstc=128806538.0a7349ff9b8d9815d341d9918ce273dc.1387967455759.1387967455759.1387967455759.1; __hssrc=1; __hssc=128806538.2.1387967455760; hubspotutk=0a7349ff9b8d9815d341d9918ce273dc; __utma=83094165.348077411.1387967454.1387967454.1387967454.1; __utmb=83094165.10.9.1387967936052; __utmc=83094165; __utmz=83094165.1387967454.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)
'Host':'www.readspeaker.com',
'Origin':'http://www.readspeaker.com',
'Referer':'http://www.readspeaker.com/voice-demo/',
# User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/31.0.1650.63 Chrome/31.0.1650.63 Safari/537.36
'X-Requested-With':'XMLHttpRequest',
               }
    url = '/content/proxy.php'
    cpath = ''
    for i in re.split(r'[\\/]', path)[:-1]:
        cpath = os.path.join(cpath, i)
        if not os.path.exists(cpath):
            os.mkdir(cpath)
    maypath = os.path.join('sound/english', os.path.split(path)[-1])
    if os.path.exists(path):
        print 'Exists: %s' % path
        return
    else:
        if os.path.exists(maypath):
            shutil.copyfile(maypath, path)
            print 'Copy: %s' % path
            return
    time.sleep(0.1)
    connection = httplib.HTTPConnection("www.readspeaker.com")
    connection.request("POST", url, urllib.urlencode(params), headers)
    response = connection.getresponse()
    if response.status == 200:
        link = json.loads(response.read())['links']['mp3'].split('/', 3)
        host = link[2]
        url = '/' + link[3]
        connection = httplib.HTTPConnection(host)
        connection.request("POST", url)
        response = connection.getresponse()
        if response.status == 200:
            mp3 = response.read()
            f = open(path, 'w')
            f.write(mp3)
            f.close()
            print 'Loaded: %s' % path
    else:
        print 'Error: %s' % path
        print response.status, response.read()

for l in translations.__all__:
#     try:
        dst_lang = __import__('translations.%s.%s' % (l, lang), fromlist=lang)
        src_lang = __import__('translations.%s.%s' % (l, 'en'), fromlist='en')
        for i in range(len(src_lang.items)):
            j = src_lang.items[i]
            j = re.sub(r'\s+|-', '_', j)
            j = re.sub(r'\W+', '', j).lower().strip('_')
            j = os.path.join('sound', lang, l, '%s.mp3' % j)
            fetchMp3(j, dst_lang.items[i], lang)
#     except:
#         print 'Error: %s, %s' % (lang, l),
#         if i in dst_lang.items:
#             print i
